package com.gitee.mazhenggg.demo.auth.config;

import com.gitee.mazhenggg.demo.auth.handle.AuthLoginFailureHandler;
import com.gitee.mazhenggg.demo.auth.handle.AuthLoginSuccessHandler;
import com.gitee.mazhenggg.demo.auth.handle.AuthLogoutSuccessHandler;
import com.gitee.mazhenggg.demo.auth.service.UserDetailsServiceImpl;
import lombok.SneakyThrows;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.builders.WebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;


@Configuration
public class WebSecurityConfigurer extends WebSecurityConfigurerAdapter {
	@Autowired
	UserDetailsServiceImpl userDetailsService;

	@Autowired
	AuthLoginFailureHandler authLoginFailureHandler;

	@Autowired
	AuthLoginSuccessHandler authLoginSuccessHandler;

	@Autowired
	AuthLogoutSuccessHandler authLogoutSuccessHandler;


	@Override
	public void configure(WebSecurity web) {
		web.ignoring().antMatchers("/css/**");
	}


	@Bean
	@Override
	@SneakyThrows
	public AuthenticationManager authenticationManagerBean() {
		return super.authenticationManagerBean();
	}

	@Override
	@SneakyThrows
	protected void configure(HttpSecurity http){
		configAuthorizeRequests(http);
		configFormLogin(http);
		//configRememberMe(http);
		//configSession(http);
		//configLogout(http);
		// 其他配置
		http.csrf().disable();
//				//验证码拦截
//				.apply(validateCodeSecurityConfig)
//				.and()
//				// 手机号短信登录
//				.apply(smsCodeAuthenticationSecurityConfig)
//				.and()
//				.exceptionHandling()
				// 未登录跳转地址
				//.authenticationEntryPoint(authenticationEntryPoint);
//                .and()
//                .addFilter(casAuthenticationFilter)
//                .addFilterBefore(singleSignOutFilter, CasAuthenticationFilter.class)
//                .addFilterBefore(requestSingleLogoutFilter, LogoutFilter.class);

	}



	private void configAuthorizeRequests(HttpSecurity http) throws Exception {
		http.authorizeRequests()
				.antMatchers("/auth/login",
						"/auth/logout",
						"/auth/mobile",
						"/login/cas",
						"/code/*",
						"/self/*",
						"/v2/api-docs",
						"/v3/*",
						"/configuration/ui",
						"/swagger-resources/**",
						"/configuration/security",
						"/swagger-ui.html",
						"/webjars/**",
						"/actuator/**")
				.permitAll()
				.anyRequest()
				.authenticated();
	}

	private void configFormLogin(HttpSecurity http) throws Exception {
		http.formLogin()
				// 登录请求地址
				.loginProcessingUrl("/auth/login")
				.usernameParameter("username")
				.passwordParameter("password")
				// 登录成功跳转地址
				.successHandler(authLoginSuccessHandler)
				// 登录失败跳转地址
				.failureHandler(authLoginFailureHandler);
	}

//	// 配置记住我相关
//	private void configRememberMe(HttpSecurity http) throws Exception {
//		http.rememberMe()
//				.tokenRepository(persistentTokenRepository)
//				.tokenValiditySeconds(securityProperties.getRememberMe().getRememberMeSeconds())
//				.userDetailsService(userDetailsService);
//	}
//
//	// 配置session管理
//	private void configSession(HttpSecurity http) throws Exception {
//		http.sessionManagement()
//				.invalidSessionStrategy(invalidSessionStrategy)
//				//最大session并发数量1
//				.maximumSessions(securityProperties.getSession().getMaximumSessions())
//				//之后的登录是否踢掉之前的登录
//				.maxSessionsPreventsLogin(securityProperties.getSession().isMaxSessionsPreventsLogin())
//				.expiredSessionStrategy(sessionInformationExpiredStrategy)
//				.sessionRegistry(sessionRegistry());
//
//	}

//	// 配置退出登录操作
//	private void configLogout(HttpSecurity http) throws Exception {
//		http.logout()
//				.logoutUrl(SecurityConstants.DEFAULT_SIGN_OUT_PROCESSING_URL_FORM)
//				// 默认就是true
//				.clearAuthentication(true)
//				// 默认就是true
//				.invalidateHttpSession(true)
//				.logoutSuccessHandler(logoutSuccessHandler)
//				.deleteCookies(SecurityConstants.DEFAULT_SIGN_OUT_COOKIE_NAMES);
//	}



//	@Override
//	protected void configure(AuthenticationManagerBuilder auth) throws Exception {
//		CustomUsernamePasswordAuthenticationProvider customProvider =
//				new CustomUsernamePasswordAuthenticationProvider();
//		customProvider.setUserDetailsService(userDetailsService);
//		customProvider.setPasswordEncoder(passwordEncoder());
//		auth.authenticationProvider(customProvider);
//	}

	@Bean
	public PasswordEncoder passwordEncoder() {
		return new BCryptPasswordEncoder();
	}

//	@Bean
//	public PasswordEncoder passwordEncoder() {
//		return PasswordEncoderFactories.createDelegatingPasswordEncoder();
//	}
//	@Bean
//	public SessionRegistry sessionRegistry(){
//		// TODO 需要重新实现此类，由于使用map存的数据，每次重启都会导致数据丢失
//		return new TepSpringSessionBackedSessionRegistry<>(sessionRepository);
////        return new SessionRegistryImpl();
//	}

}
